package com.dwxt.community.service.supervisor;

import com.dwxt.common.base.*;
import com.dwxt.common.util.*;
import com.dwxt.community.aiequipment.aibin.entity.*;
import com.dwxt.community.dao.*;
import com.dwxt.community.entity.*;
import com.dwxt.community.entity.dto.*;
import com.dwxt.community.entity.enumerate.*;
import com.dwxt.community.entity.vo.*;
import com.dwxt.community.service.*;
import com.github.pagehelper.*;
import org.apache.commons.lang3.*;
import org.springframework.beans.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.*;

import java.util.*;
import java.util.stream.*;

/**
 * @author
 * @program: intelligentcity
 * @description:
 * @create: 2020/04/17
 */
@Service
public class SupervisorUserService {

    @Autowired
    private SupervisorUserMapper supervisorUserMapper;
    @Autowired
    private SupervisorTrashCanMapper supervisorTrashCanMapper;
    @Autowired
    private SupervisorRoleMapper supervisorRoleMapper;
    @Autowired
    private SupervisorHouseaddrMapper supervisorHouseaddrMapper;
    @Autowired
    private SupervisorTaskRecordMapper supervisorTaskRecordMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private RubbishBagRecordService rubbishBagRecordService;
    @Autowired
    private TrashCanMapper trashCanMapper;

    /**
     * 巡检员、督导员登录
     */
    public SupervisorUserVo login(String phone, String password) {
        SupervisorUserVo user = selectByPhone(phone);
        if (ObjectUtils.isEmpty(user)) {
            return null;
        }
        //设置需要处理的垃圾桶数
        setFullBinNum(user);
        //设置角色
        setDdyOrXjy(user);
        return MD5Utils.MD5Encode(password).equalsIgnoreCase(user.getPassword()) ? user : null;
    }

    private void setFullBinNum(SupervisorUserVo user) {
        List<TrashCan> trashCans = new ArrayList<>();

        if (StateConstant.LI_PIN_JI_GUAN_LI_YUAN.getMsg().equals(user.getSupervisorRole().getName())) {
            user.setFullBinNum(YesOrNo.NO);
        } else {
            if (StateConstant.XUN_JIAN_YUAN.getMsg().equals(user.getSupervisorRole().getName())) {
                trashCans = trashCanMapper.selectAllByXJY(user.getId());
            } else if (StateConstant.DU_DAO_YUAN.getMsg().equals(user.getSupervisorRole().getName())) {
                trashCans = trashCanMapper.selectAll(user.getId());
            }
            user.setFullBinNum(trashCans.stream().filter(trashCan -> ObjectUtils.isNotEmpty(trashCan.getStatus()) && trashCan.getStatus() == YesOrNo.YES).toArray().length);

        }
    }

    /**
     * 设置用户时否为督导员或者巡检员
     *
     * @param user
     */
    public void setDdyOrXjy(SupervisorUserVo user) {
        SupervisorRole sr = supervisorRoleMapper.selectById(user.getRoleId());
        if (StateConstant.DU_DAO_YUAN.getMsg().equals(sr.getName())) {
            user.setIsDudaoyuan(YesOrNo.YES);
            user.setIsXunjianyuan(YesOrNo.NO);
        }
        if (StateConstant.XUN_JIAN_YUAN.getMsg().equals(sr.getName())) {
            user.setIsXunjianyuan(YesOrNo.YES);
            user.setIsDudaoyuan(YesOrNo.NO);
        }
    }

    public SupervisorUserVo selectByPhone(String phone) {
        return supervisorUserMapper.selectByPhone(phone);
    }

    /**
     * 验证户主
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult verifyOwner(String id) {
        User updateUser = new User();

        //当前用户
        User user = userService.selectUserByPrimaryKey(id);
        if (ObjectUtils.isEmpty(user)){
            return BaseResult.build(StatusCode.USER_NOT_EXIST);
        }

        //验证地址是否合法
        if (StringUtils.isBlank(user.getCommunityName()) || StringUtils.isBlank(user.getHouseNumber())) {
            return BaseResult.build(StatusCode.HOUSE_ADDR_NULL);
        }

        //取消原户主 处理一个家庭地址出现多个户主的情况
        User userHouseOwner = userService.selectHouseOwnerByUserId(id);
        if (!ObjectUtils.isEmpty(userHouseOwner)) {
            if (id.equals(userHouseOwner.getId())) {
                return BaseResult.build(StatusCode.ALREADY_HOUSE_HEAD);
            }
            updateUser.setId(userHouseOwner.getId());
            updateUser.setIsHouseHead(YesOrNo.NO);
            userService.updateHouseOwner(updateUser);
        }

        updateUser.setId(user.getId());
        updateUser.setIsHouseHead(YesOrNo.YES);
        int res = userService.updateHouseOwner(updateUser);
        if (res > 0) {

            //督导员和家庭关系
            //查看该家庭地址是否已经绑定督导员
            SupervisorHouseaddr selectObj = new SupervisorHouseaddr();
            selectObj.setHouseNumber(user.getHouseNumber());
            selectObj.setCommunityName(user.getCommunityName());
            selectObj.setCommunityId(user.getCommunityId());
            SupervisorHouseaddr alreadySupervisorHouseaddr = supervisorHouseaddrMapper.selectBySupervisorHouseaddr(selectObj);
            String supervisorId = PartyUtil.getCurrentUserId();
            if (alreadySupervisorHouseaddr == null) {
                Date currDate = new Date();
                SupervisorHouseaddr supervisorHouseaddr = new SupervisorHouseaddr();
                supervisorHouseaddr.setId(IDUtils.genItemId());
                supervisorHouseaddr.setCreateTime(currDate);
                supervisorHouseaddr.setCommunityId(user.getCommunityId());
                supervisorHouseaddr.setCommunityName(user.getCommunityName());
                supervisorHouseaddr.setHouseNumber(user.getHouseNumber());
                supervisorHouseaddr.setSupervisorId(supervisorId);
                res = supervisorHouseaddrMapper.insert(supervisorHouseaddr);
            } else {
                alreadySupervisorHouseaddr.setSupervisorId(supervisorId);
                res = supervisorHouseaddrMapper.updateByPrimaryKey(alreadySupervisorHouseaddr);
            }
            if (res > 0) {
                //新增督导员工作记录记录
                SupervisorTaskRecord supervisorTaskRecord = new SupervisorTaskRecord();
                supervisorTaskRecord.setCreateTime(new Date());
                supervisorTaskRecord.setId(IDUtils.genItemId());
                supervisorTaskRecord.setSupervisorId(supervisorId);
                supervisorTaskRecord.setTaskType("验证户主");
                supervisorTaskRecord.setUserId(id);
                supervisorTaskRecordMapper.insert(supervisorTaskRecord);
            }
        }
        return BaseResult.ok();
    }

    /**
     * 获取用户
     *
     * @param id
     * @return
     */
    public BaseResult getUser(String id) {
        User user = userService.selectUserByPrimaryKey(id);
        if (user == null) {
            return BaseResult.build(StatusCode.PARAMETER_WRONG);
        }
        UserPervisorVo userPervisorVo = new UserPervisorVo();
        BeanUtils.copyProperties(user, userPervisorVo);
        //设置上次领取时间
        Date lastDate = rubbishBagRecordService.selectLastGotBagDateByUserId(id);
        userPervisorVo.setLastGotBagTime(lastDate);
        return BaseResult.ok(userPervisorVo);
    }

    /**
     * 获取巡检员下的所有督导员
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public BaseResult getCensors(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        String currentUserId = PartyUtil.getCurrentUserId();
        List<SupervisorUser> supervisorUsers = supervisorUserMapper.selectCensorsById(currentUserId);
        return BaseResult.ok(new PageInfo<>(supervisorUsers));
    }

    /**
     * 按条件返回员工（督导员、巡检员）列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public List<SupervisorUserVo> selectAll(Integer pageNum, Integer pageSize, String workId, String roleName, String username) {
        PageHelper.startPage(pageNum, pageSize);
        SupervisorUserVo svo = new SupervisorUserVo();
        svo.setWorkId(workId);
        svo.setUsername(username);
        SupervisorRole supervisorRole = new SupervisorRole();
        supervisorRole.setName(roleName);
        svo.setSupervisorRole(supervisorRole);
        return supervisorUserMapper.selectAll(svo);
    }

    /**
     * 添加新员工
     *
     * @param supervisorUser
     * @return
     */
    public BaseResult insertOrUpdate(SupervisorUserDto supervisorUser) {
        //重复验证
        BaseResult result = valityRepetition(supervisorUser);
        if (!result.getStatus().equals(StatusCode.SUCCESS.getStatus())) {
            return result;
        }

        //角色验证
        String roleId = supervisorUser.getRoleId();
        SupervisorRole supervisorRole = supervisorRoleMapper.selectById(roleId);

        if (StateConstant.DU_DAO_YUAN.getMsg().equals(supervisorRole.getName())) {
            if (StringUtils.isBlank(supervisorUser.getSuperiorId()) || "-1".equals(supervisorUser.getSuperiorId())) {
                return BaseResult.build(StatusCode.NOT_SET_SUPERIOR);
            }
            List<SupervisorUser> supervisorUsers = supervisorUserMapper.selectBySuperiorId(supervisorUser.getId());
            if (supervisorUsers.size() > 0) {
                return BaseResult.build(StatusCode.EXIST_SUPERVISOR_USER);
            }
        }

        if (StateConstant.XUN_JIAN_YUAN.getMsg().equals(supervisorRole.getName())) {

            supervisorUser.setSuperiorId(null);
            supervisorUser.setSumUpDoorPropaganda(0);
        }
        if (StateConstant.LI_PIN_JI_GUAN_LI_YUAN.getMsg().equals(supervisorRole.getName())) {

            supervisorUser.setSuperiorId("-1");
            supervisorUser.setSumUpDoorPropaganda(0);
        }

        //配置督导员和垃圾桶的关系
        List<SupervisorTrashCan> supervisorTrashCans = supervisorUser.getSupervisorTrashCans();
        Date currDate = new Date();
        if (supervisorTrashCans != null && supervisorTrashCans.size() > 0) {
            for (SupervisorTrashCan stc : supervisorTrashCans) {
                supervisorTrashCanMapper.deleteBySupervisorId(supervisorUser.getId());
                stc.setId(IDUtils.genItemId());
                stc.setSupervisorId(supervisorUser.getId());
                stc.setCreateTime(currDate);
                stc.setUpdateTime(currDate);
                supervisorTrashCanMapper.insert(stc);
            }
        }

        //新增
        if (StringUtils.isBlank(supervisorUser.getId())) {
            if (StringUtils.isBlank(supervisorUser.getNewPassword())) {
                return BaseResult.build(StatusCode.PASSWORD_EXIST);
            }
            supervisorUser.setPassword(MD5Utils.MD5Encode(supervisorUser.getNewPassword().trim()));
            supervisorUser.setId(IDUtils.genItemId());
            supervisorUser.setUseing(YesOrNo.YES);
            supervisorUser.setCreateTime(currDate);
            supervisorUser.setUpdateTime(currDate);
            return BaseResult.ok(supervisorUserMapper.insert(supervisorUser));
            //更新
        } else {
            //修改密码
            if (!StringUtils.isBlank(supervisorUser.getNewPassword())) {
                supervisorUser.setPassword(MD5Utils.MD5Encode(supervisorUser.getNewPassword().trim()));
            }
            supervisorUserMapper.updateByPrimaryKey(supervisorUser);
        }
        return BaseResult.ok();
    }

    /**
     * 员工角色列表
     *
     * @return
     */
    public List<SupervisorRole> getRole() {
        return supervisorRoleMapper.getRole();

    }

    /**
     * 验证重复
     */
    public BaseResult valityRepetition(SupervisorUser supervisorUser) {
        SupervisorUserVo valityObj = new SupervisorUserVo();
        valityObj.setId(supervisorUser.getId());
        //验证工号重复
        valityObj.setWorkId(supervisorUser.getWorkId());
        if (supervisorUserMapper.valityRepetition(valityObj).size() > 0) {
            return BaseResult.build(StatusCode.WORK_ID_EXIST);
        }
        valityObj.setWorkId(null);

        //验证电话号重复
        valityObj.setPhone(supervisorUser.getPhone());
        if (supervisorUserMapper.valityRepetition(valityObj).size() > 0) {
            return BaseResult.build(StatusCode.PHONE_EXIST);
        }
        valityObj.setPhone(null);

        //验证身份证重复
        valityObj.setIdCard(supervisorUser.getIdCard());
        if (supervisorUserMapper.valityRepetition(valityObj).size() > 0) {
            return BaseResult.build(StatusCode.ID_CARD_EXIST);
        }
        valityObj.setIdCard(null);

        return BaseResult.ok();
    }


    /**
     * 员工工作记录
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public BaseResult workRecord(Integer pageNum,
                                 Integer pageSize,
                                 String workId,
                                 String phone,
                                 String taskType) {
        PageHelper.startPage(pageNum, pageSize);
        SupervisorTaskRecordVo str = new SupervisorTaskRecordVo();
        str.setWorkId(workId);
        str.setPhone(phone);
        str.setTaskType(taskType);
        List<SupervisorTaskRecordVo> supervisorTaskRecords = supervisorTaskRecordMapper.selectAll(str);
        return BaseResult.ok(new PageInfo<>(supervisorTaskRecords));
    }

    /**
     * 员工详情
     *
     * @param id
     * @return
     */
    public SupervisorUser detail(String id) {
        return supervisorUserMapper.selectDetailByPrimaryKey(id);
    }

    public BaseResult workRecordDetail(String id) {
        return BaseResult.ok(supervisorTaskRecordMapper.selectWorkRecordDetailByPrimaryKey(id));

    }

    /**
     * 删除任务记录
     *
     * @param id
     * @return
     */
    public BaseResult delWorkRecord(String id) {
        return BaseResult.ok(supervisorTaskRecordMapper.deleteByPrimaryKey(id));
    }

    public List<SupervisorUser> getXunjinayuan(String id) {
        return supervisorUserMapper.selectXunjinayuan(id);
    }

    /**
     * 启用或者停用
     *
     * @param id
     * @return
     */
    public int useOrStop(String id) {
        SupervisorUser supervisorUser = supervisorUserMapper.selectByPrimaryKey(id);
        if (YesOrNo.YES == supervisorUser.getUseing()) {
            supervisorUser.setUseing(YesOrNo.NO);
        } else {
            supervisorUser.setUseing(YesOrNo.YES);
        }
        return supervisorUserMapper.updateByPrimaryKeySelective(supervisorUser);
    }

    /**
     * 修改督导员和垃圾桶关系表
     *
     * @param supervisorId
     * @param deviceIds
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult updateSupervisorTrashCan(String supervisorId, String... deviceIds) {
        SupervisorUser supervisorUser = supervisorUserMapper.selectByPrimaryKey(supervisorId);
        if (ObjectUtils.isEmpty(supervisorUser)) {
            return BaseResult.build(StatusCode.USER_NOT_EXIST);
        }
       /* ArrayList<SupervisorTrashCan> supervisorTrashCans = new ArrayList<>();
        for (String deviceId : deviceIds) {
            SupervisorTrashCan supervisorTrashCan = new SupervisorTrashCan();
            supervisorTrashCan.setSupervisorId(supervisorId);
            supervisorTrashCan.setDeviceId(deviceId);
            supervisorTrashCan.setCreateTime(currdate);
            supervisorTrashCan.setUpdateTime(currdate);
            supervisorTrashCan.setId(IDUtils.genItemId());
            supervisorTrashCans.add(supervisorTrashCan);
        }
        int del = supervisorTrashCanMapper.deleteByDeviceId(deviceIds);
        int insert = supervisorTrashCanMapper.batchInsert(supervisorTrashCans);*/
        Date currDate = new Date();
        if (deviceIds != null && deviceIds.length > 0) {
            List<SupervisorTrashCan> supervisorTrashCan = supervisorTrashCanMapper.selectBySupervisorId(supervisorUser.getId());
            for (String deviceId : deviceIds) {
                if (!supervisorTrashCan.stream().map(SupervisorTrashCan::getDeviceId).collect(Collectors.toList()).contains(deviceId)) {
                    SupervisorTrashCan stc = new SupervisorTrashCan();
                    stc.setId(IDUtils.genItemId());
                    stc.setDeviceId(deviceId);
                    stc.setSupervisorId(supervisorUser.getId());
                    stc.setCreateTime(currDate);
                    stc.setUpdateTime(currDate);
                    supervisorTrashCanMapper.insert(stc);
                }
            }
            for (SupervisorTrashCan stc : supervisorTrashCan) {
                if (!Arrays.asList(deviceIds).contains(stc.getDeviceId())) {
                    supervisorTrashCanMapper.deleteByPrimaryKey(stc.getId());
                }
            }
        }
        return BaseResult.ok();
    }
}
